package handler

import (
	"2302a/tiktok_business/internal/dao"
	"2302a/tiktok_business/internal/model"
	"2302a/tiktok_business/pkg"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"strconv"
	"sync"
)

type Message struct {
	ReceiverId string `form:"receiver_id" json:"receiver_id"` // 用户1
	SenderId   string `form:"sender_id" json:"sender_id"`     // 用户2
}
type Name struct {
	Conn *websocket.Conn
	Data chan []byte
	msg  *Message
}

var clineMap map[string]*Name = make(map[string]*Name, 0)
var wg sync.WaitGroup

func Chat(c *gin.Context) {
	var chat Message
	_ = c.ShouldBind(&chat)
	receiverId := chat.ReceiverId
	senderId := chat.SenderId
	upgrade := websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	conn, err := upgrade.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		atop, _ := strconv.Atoi(chat.ReceiverId)
		log.Println(atop)
		if atop == 10 {
			log.Printf("WebSocket 连接失败 :%v", err)
			_ = conn.WriteMessage(websocket.TextMessage, nil)
			return
		} else {
			log.Println("WebSocket1 连接失败", err)
			return
		}

	}
	var msg = &Message{
		ReceiverId: receiverId,
		SenderId:   senderId,
	}
	var code = &Name{
		Conn: conn,
		Data: make(chan []byte, 100),
		msg:  msg,
	}

	clineMap[receiverId+"_"+senderId] = code
	wg.Add(4)
	go SendMessage(code, msg)
	go ReverseMessage(code, msg)

}

func SendMessage(code *Name, msg *Message) {
	defer wg.Done()
	defer wg.Wait()
	for {
		select {
		case data := <-code.Data:
			//var follow model.Follows
			//if follow.Status == 1 {
			//_ = code.Conn.WriteMessage(websocket.TextMessage, []byte("已关注"))
			res := pkg.SensitiveClient(string(data))
			if res {

				atom, err := strconv.Atoi(string(data))
				log.Println(atom)

				if atom == 10 {
					if err != nil {
						_ = code.Conn.WriteMessage(websocket.TextMessage, nil)
						return
					} else {
						_ = code.Conn.WriteMessage(websocket.TextMessage, data)
						log.Println("消息发送失败", err)
						return
					}

				}
			} else {
				log.Println("消息不合法")
			}
			//}
			//if follow.Status == 0 {
			//	_ = code.Conn.WriteMessage(websocket.TextMessage, []byte("取消关注"))
			//	return
			//}

			CreatedCharMessage(msg.ReceiverId, msg.SenderId, data)
		}

	}
}
func CreatedCharMessage(userId string, senderId string, data []byte) {
	parseUint, _ := strconv.ParseUint(userId, 10, 64)
	SenderUint, _ := strconv.ParseUint(senderId, 10, 64)

	dao.Create(&model.Messages{
		ReceiverId: uint(parseUint),
		SenderId:   uint(SenderUint),
		MType:      1,
		Content:    string(data),
	})

}
func ReverseMessage(code *Name, msg *Message) {
	defer wg.Done()
	defer wg.Wait()
	receiverId := msg.ReceiverId
	senderId := msg.SenderId
	for {
		_, message, err := code.Conn.ReadMessage()
		log.Println(message)
		if err != nil {
			log.Println("接受消息失败", err)
			return
		}
		if name, ok := clineMap[senderId+"_"+receiverId]; ok {
			name.Data <- message
		}
	}
}
